import React from 'react';
import Button from "../../../../node_modules/react-bootstrap/lib/Button";
import ListGroup from "react-bootstrap/lib/ListGroup";
import ListGroupItem from "react-bootstrap/lib/ListGroupItem";
import Input from "react-bootstrap/lib/Input";
import LeftNav from '../../../../node_modules/material-ui/lib/left-nav';
import Path from '../../lib/path.js';
import Modal from "../../../../node_modules/react-bootstrap/lib/Modal";
import OverlayTrigger from "react-bootstrap/lib/OverlayTrigger";
import Popover from "react-bootstrap/lib/Popover";
import HttpRequest from './../HttpRequest.js';
import Panel from 'react-bootstrap/lib/Panel';


var BuildResultTab = React.createClass({
    getInitialState: function () {
        return ({
            current_project: this.props.current_project, //当前项目
            ListData: [], //构建配置数据
            ListItems: [], //左侧构建配置列表
            buildResult: [],
            current_selected: null //当前选中配置
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_project: newProps.current_project,
            current_selected: null
        }, this.componentDidMount());
    },

    componentDidMount: function () {
        var ob = this;
        //msgFrontAgent.onConnected(function () {
        //        msgFrontAgent.order('build_state_update', function () {
        //            ob._renderBuildResultTable();
        //        })
        //    }
        //);
        HttpRequest.getAllBuildConfigs().success(function (configs) {
            if (configs.code == 0) {
                var listData = _.remove(configs.data, function (o) {
                    return o.project == ob.state.current_project._id;
                });
                ob.setState({
                    ListData: listData
                }, ob._renderList)
            }
        }).error(function (err) {
            toastr.error(null, "获取构建配置失败", {timeOut: 0});
        });
        ob._renderBuildResultTable();
        setInterval(
            function () {
                if(ob.refs.buildConfig){
                    ob._renderBuildResultTable();
                    console.log("refreshed");
                }
            }
            ,2000);
    },
    itemSelected: function (config_id) {
        HttpRequest.getBuildConfigInfo(config_id).success(function (res) {
            if (res.code == 500) {
                toastr.error(null, res.message);
            } else {
                this.setState({
                    current_selected: res.data
                }, function () {
                    this._renderBuildResultTable()
                });
            }
        }.bind(this)).error(function (err) {

        });
    },
    executeBuilding: function () {
        var data = {
            config: this.state.current_selected._id
        };
        HttpRequest.executeBuilding(data).success(function (resp) {
            if (resp.code != 500) {
                toastr.success(null, "构建发起成功");
            } else {
                toastr.error(null, "构建发起失败");
            }
        }).error(function () {
            toastr.error(null, "构建发起失败");
        });
    },
    _renderList: function () {
        var items = [];
        this.state.ListData.map(function (item) {
            items.push(
                <option value={item._id} key = {item._id}>{item.title}</option>
            );
        }.bind(this));
        this.setState({
            ListItems: items
        });
    },
    onItemSelected: function (item, index) {
        this.setState({"selectedIndex": index}, this._renderBuildResultTable);
    },
    deleteBuildResult: function (index, buildId) {
        this.setState({"selectedIndex": index}, this._renderBuildResultTable);
        confirm("确定删除？",function(){
                HttpRequest.deleteBuildResult(buildId).success(function (resp) {
                    if (resp.code != 500) {
                        this.componentDidMount();
                    } else {
                        toastr.error(null, "删除失败");
                    }
                }.bind(this)).error(function () {
                    toastr.error(null, "删除失败");
                });
        }.bind(this));
    },
    //cancelBuilding:function(){
    //    var that = this;
    //    var index = that.state.selectedIndex;
    //    //that.state.ListData[
    //    if(index && that.state.ListData[index] && that.state.ListData[index].state != 'building'){
    //        var build = that.state.ListData[index];
    //        HttpRequest.cancelBuilding(build).success(function (resp) {}).error(function(){
    //
    //        });
    //    }else{
    //        toastr.warning(null, "请先选择一条正在构建的任务");
    //    }
    //},
    _renderBuildResultTable: function () {
        //根据构建配置ID获得构建结果 （下载 删除操作）
        //根据current_selected获取
        //var oldTime = (new Date("2011/11/11 20:10:10")).getTime(); //得到毫秒数
        //var newTime = new Date(oldTime); //就得到普通的时间了
        var ob = this;
        var builds = [];
        var options = {
            config: ob.refs["buildConfig"].getValue(),
            type: ob.refs["buildType"].getValue(),
            result: ob.refs["buildResult"].getValue(),
            //startTime: ob.refs["startTime"].getValue(),
            //endTime: ob.refs["endTime"].getValue()
        };
        HttpRequest.getAllBuilds().success(function (resp) {
            if (resp.code != 500) {
                var tableData;
                tableData = _.remove(resp.data, function (o) {
                    return o.project == ob.state.current_project._id;
                });
                tableData.map(function (build) {
                    //从构建配置获取构建类型和构建名称
                    var index = _.findIndex(ob.state.ListData, function (cfg) {
                        return cfg._id == build.config;
                    });
                    if (index >= 0) {
                        build['type'] = ob.state.ListData[index].type;
                        build['title'] = ob.state.ListData[index].title;
                    }
                    //获取buildState 和 buildResult
                    switch (build.state) {
                        case "created":
                            build['buildState'] = "已创建";
                            break;
                        case "readying":
                            build['buildState'] = "准备中";
                            break;
                        case "building":
                            build['buildState'] = "构建中";
                            break;
                        case "error":
                            build['buildState'] = "出现错误";
                            break;
                        case "completing":
                            build['buildState'] = "构建结果下载中";
                            break;
                        case "completed":
                            build['buildState'] = "已完成";
                            break;
                        case "canceled":
                            build['buildState'] = "已取消";
                            break;
                        case "canceling":
                            build['buildState'] = "正在取消";
                            break;
                    }
                    switch (build.result) {
                        case "SUCCESS":
                            build['buildResult'] = "构建成功";
                            break;
                        case "FAILED":
                            build['buildResult'] = "构建失败";
                            break;
                    }

                });

                if (options.config != "no") {
                    tableData = _.remove(tableData, function (o) {
                        return o.config == options.config;
                    });
                }
                if (options.result != "all") {
                    tableData = _.remove(tableData, function (o) {
                        return o.result == options.result;
                    });
                }

                if (options.type != 'all') {
                    tableData = _.remove(tableData, function (o) {
                        var type = o.type;
                        switch (type) {
                            case "mk_back":
                                type = "mk";
                                break;
                            case "app_android":
                                type = "app";
                                break;
                            case "app_ios":
                                type = "app";
                                break;
                        }
                        ;
                        return type == options.type;
                    });
                }
                var details;
                tableData.map(function (build, index) {
                    //if (build.state == "completed") {
                    //    details =
                    //        <div>
                    //            <strong>编译警告：</strong>{build.result_detail?build.result_detail.compileWarning:""}<br/>
                    //            <strong>编译错误：</strong>{build.result_detail?build.result_detail.compileError:""}<br/>
                    //            <strong>开始时间：</strong>{(new Date(build.result_detail.startTime)).toLocaleString()}<br/>
                    //            <strong>结束时间：</strong>{(new Date(build.result_detail.finishTime)).toLocaleString()}
                    //        </div>
                    //} else if (build.state == "error") {
                    //    details =
                    //        <div>
                    //            <strong>构建失败：</strong>{build.state_info}
                    //        </div>
                    //}
                    var style = {borderBottom: "#f2f2f2 1px solid", height: "50px", fontSize: "15px"};
                    var img_del = "/res/image/delete.png";
                    var info_style = {
                        width: "23px",
                        height: "23px",
                        display: "inline-block",
                        marginLeft: "5px",
                        marginTop: "-1px",
                        color: "#EBEBEB"
                    };

                    if (index == this.state.selectedIndex) {
                        style = {
                            backgroundColor: "#f3f3f3",
                            borderBottom: "#f2f2f2 1px solid",
                            height: "50px",
                            fontSize: "15px"
                        };
                        info_style = {
                            width: "23px",
                            height: "23px",
                            display: "inline-block",
                            marginLeft: "5px",
                            marginTop: "-1px",
                            color: "#FF9600"
                        };
                        img_del = "/res/image/delete_h.png"
                    } else {
                        img_del = "/res/image/delete.png"
                    }
                    builds.push(
                        <tr id={"table_item_" + index}
                            key = {index}
                            onClick={this.onItemSelected.bind(this,build,index)}
                            style={style}
                        >
                            <td style={{width:"25%",cursor:"pointer",paddingLeft:"20px"}}>{build.title}</td>
                            <td style={{width:"25%",cursor:"pointer"}}>{build.buildState}</td>
                            <td style={{width:"25%",cursor:"pointer"}}>{build.buildResult}</td>
                            <td style={{width:"25%",cursor:"pointer",marginLeft:"5px"}}>
                                <span style={{display:"inline-block"}}>

                                    <img
                                        onClick={function(){this.deleteBuildResult(index,build._id)}.bind(this)}
                                        src={img_del}
                                        style={{cursor:"pointer",float:"left"}}
                                    />
                                </span>
                            </td>
                        </tr>
                    );
                }.bind(this));
                this.setState({
                    buildResult: builds
                })

            } else {
                toastr.error(null, "获取构建结果失败！");
            }
        }.bind(this)).error(function (error) {
            toastr.error(null, "获取构建结果失败:" + JSON.stringify(error));
        });
    },
    render: function () {
        var buildRes = null;
        if (this.state.buildResult.length > 0) {
            buildRes =
                <div style={{height:"100%"}}>
                    <table style={{fontSize:16,width:"100%",background:"#ffffff",marginTop:"20px"}}>
                        <tbody>
                        <tr style={{backgroundColor: "#e3e3e3",opacity: "0.8",borderBottom: "#f2f2f2 1px solid",height: "50px",fontSize: "15px"}}>
                            <th style={{paddingLeft:"20px",width:"25%",cursor:"pointer"}}>配置名称</th>
                            <th style={{width:"25%",cursor:"pointer"}}>构建状态</th>
                            <th style={{width:"25%",cursor:"pointer"}}>构建结果</th>
                            <th style={{width:"25%"}}>操作</th>

                        </tr>
                        </tbody>
                    </table>
                    <div style={{overflowY:"auto", height:"calc(100% - 30px)"}}>
                        <table style={{fontSize:16,width:"100%",background:"#ffffff"}}>
                            <tbody>
                            {this.state.buildResult}
                            </tbody>
                        </table>
                    </div>
                </div>
        } else {
            buildRes = <div style={{textAlign:"center"}}>
                <div style={{color:"#969696",marginTop:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>
                    <i className="fa fa-exclamation-circle"
                       style={{fontSize:"48px",cursor:"pointer"}}/>
                    <br/>
                    没有符合查询条件的构建结果！
                </div>
            </div>
        }
        return (
            <div style={{height:"100%"}}>
                <div className="content_pageLeft">
                    <span className="info_title" style={{paddingLeft:"30px"}}>筛选条件</span>
                    <div
                        style={{width:"80%",height:"calc(100% - 65px)",maxHeight:"80%",overflowY:"auto",marginLeft: "10%",marginTop: "20px"}}>
                        <Input bsSize="small"
                               ref="buildConfig"
                               type="select"
                               onChange={()=>{this._renderBuildResultTable()}}
                               label="构建配置"
                               defaultValue="all">
                            <option value="no">--所有构建配置--</option>
                            {
                                this.state.ListItems
                            }
                        </Input>
                        <Input bsSize="small"
                               ref="buildType"
                               type="select"
                               label="构建类型"
                               onChange={()=>{this._renderBuildResultTable()}}
                               defaultValue="all">
                            <option value="mk">MK构建</option>
                            <option value="app">移动构建</option>
                            <option value="all">所有构建</option>
                        </Input>

                        <Input bsSize="small"
                               type="select"
                               ref="buildResult"
                               label="构建结果"
                               onChange={()=>{this._renderBuildResultTable()}}
                               defaultValue="all">
                            <option value="SUCCESS">成功</option>
                            <option value="FAILED">失败</option>
                            <option value="all">所有</option>
                        </Input>


                    </div>
                </div>
                <div className="content_pageRight">
                    <span className="info_title">构建结果</span>
                    <div style={{width:"100%",height:"calc(100% - 63px)",marginTop: "20px"}}>
                        {buildRes}

                    </div>

                </div>

            </div>
        );
    }
});
export default BuildResultTab;